﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.UI;

namespace WorkRecord.CommonClass
{
    public class WebContext : Page
    {
        /// <summary>
        /// 上下文缓存
        /// </summary>
        private static Dictionary<object, WebContext> CachedContext
        {
            get
            {
                return cachedContext;
            }
        }

        private static Dictionary<object, WebContext> cachedContext = new Dictionary<object, WebContext>();


        public WebContext()
        {
            if (HttpContext.Current == null) return;

            if (HttpContext.Current.Handler == null) return;

            var current = HttpContext.Current.Handler as Page;
            object objKey = HttpContext.Current;
            if (cachedContext.ContainsKey(objKey))
            {
                cachedContext[objKey] = this;
            }
            else
            {
                lock (cachedContext)
                {
                    cachedContext.Add(objKey, this);
                }
            }
            if (current != null)
            {
                current.Unload += current_Disposed;
            }
        }

        public static WebContext Current
        {
            get
            {
                WebContext current;
                object keyObject;
                if (HttpContext.Current != null)
                {
                    keyObject = HttpContext.Current;
                }
                else
                {
                    keyObject = Process.GetCurrentProcess();
                }
                if (!cachedContext.TryGetValue(keyObject, out current))
                {
                    current = new WebContext();
                }
                return current;
            }
        }


        private DataTable currentUser;
        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        public DataTable CurrentUser
        {
            get
            {
                if (currentUser != null && currentUser.Rows.Count > 0) return currentUser;

                var userAccount = string.Empty;

                //if (HttpContext.Current.Request.Cookies["UserAccount"] != null)
                //{
                //    userAccount = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["UserAccount"].Value);
                //}
                if (Session["UserAccount"] != null)
                {
                    userAccount = Session["UserAccount"].ToString();
                }

                DataTable user = null;
                if (!string.IsNullOrEmpty(userAccount))
                    user = new DataAccess().readdata("select * from T_Sys_User where username='" + userAccount + "'");
                if (user == null || user.Rows.Count <= 0)
                {
                    HttpContext.Current.Response.Redirect("/Login.aspx?ReturnUrl=" +
                                                          HttpContext.Current.Request.Url.PathAndQuery + "");
                }
                currentUser = user;
                return user;
            }
            set
            {
                currentUser = value;
            }
        }


        private bool _isAdministrator = false;

        public bool IsAdministrator
        {
            get
            {
                if (_isAdministrator) return true;
                if (CurrentUser != null && CurrentUser.Rows.Count > 0)
                {
                    var username = CurrentUser.Rows[0]["username"].ToString().ToLower();
                    var arr = ConfigurationManager.AppSettings["Admin"].Split(';');
                    foreach (var account in arr)
                    {
                        if (account.ToLower() == username)
                        {
                            _isAdministrator = true;
                            break;
                        }
                    }
                }
                return _isAdministrator;
            }
        }


        #region 销毁事件
        /// <summary>
        /// 实例销毁事件
        /// 释放K2连接，删除缓存WebContext实例
        /// </summary>
        /// <param name="sender">事件调用者</param>
        /// <param name="e">事件参数</param>
        void current_Disposed(object sender, EventArgs e)
        {
            try
            {

                object key = HttpContext.Current;
                lock (cachedContext)
                {
                    cachedContext.Remove(key);
                }
            }
            catch
            {
            }
        }
        #endregion
    }
}